package com.sxpi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sxpi.common.result.Result;
import com.sxpi.convert.CostumesConvert;
import com.sxpi.convert.StoreItemConvert;
import com.sxpi.convert.StoresConvert;
import com.sxpi.mapper.*;
import com.sxpi.model.entity.*;
import com.sxpi.model.entity.CostumesVo;
import com.sxpi.model.vo.StoreItemVo;
import com.sxpi.model.vo.StoresVo;
import com.sxpi.service.CostumesService;
import com.sxpi.utils.FileUtil;
import com.sxpi.utils.MinioUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;

@Service
public class CostumesServiceImpl implements CostumesService {
    @Resource
    private CostumesMapper costumesMapper;
    @Resource
    private CostumeImagesMapper costumeImagesMapper;
    @Resource
    private StoreItemMapper storeItemMapper;
    @Resource
    private StoresMapper storesMapper;
    @Resource
    private StoreImagesMapper storeImagesMapper;
    @Resource
    private LikesMapper likesMapper;
    @Autowired
    private MinioUtils minioUtils;
    //上传文件路径
    @Value("${uploadFile.path}")
    private String uploadDir;


    @Override
    public List<CostumesVo> getByCategoryId(Long id, Long userId) {
        LambdaQueryWrapper<Costumes> eq = new LambdaQueryWrapper<Costumes>().eq(Costumes::getId, id);
        List<Costumes> costumes = costumesMapper.selectList(eq);
        List<CostumesVo> costumesVos = CostumesConvert.INSTANCE.convertVoToEntityList(costumes);
        costumesVos.forEach(costumesVo -> {
            LambdaQueryWrapper<CostumeImages> eq1 = new LambdaQueryWrapper<CostumeImages>().eq(CostumeImages::getCostumeId, costumesVo.getId());
            List<CostumeImages> costumeImages = costumeImagesMapper.selectList(eq1);
            costumesVo.setSonUrl(costumeImages.stream().map(CostumeImages::getUrl).toList());

            if (userId!= null) {
                LambdaQueryWrapper<Likes> likesQueryWrapper = new LambdaQueryWrapper<Likes>()
                       .eq(Likes::getUserId, userId)
                       .eq(Likes::getCostumesId, id);
                boolean isLiked = likesMapper.exists(likesQueryWrapper);
//                System.out.println("isLiked是"+isLiked);
                costumesVo.setIsLike(isLiked? 1 : 0);
            } else {
                costumesVo.setIsLike(0);
            }
        });
        return costumesVos;
    }
    @Override
    public List<StoresVo> getStores(Long id) {
        LambdaQueryWrapper<StoreItem> eq = new LambdaQueryWrapper<StoreItem>().eq(StoreItem::getCostumesId, id);
        List<StoreItem> storeItems = storeItemMapper.selectList(eq);
        List<StoreItemVo> storeItemVos = StoreItemConvert.INSTANCE.convertEntityToVo(storeItems);
        List<StoresVo> storesVos = new ArrayList<>();

        storeItemVos.forEach(storeItemVo->{
            LambdaQueryWrapper<StoreImages> eq1 = new LambdaQueryWrapper<StoreImages>().eq(StoreImages::getStoreId, storeItemVo.getStoreId());
            List<StoreImages> storeImages = storeImagesMapper.selectList(eq1);
            LambdaQueryWrapper<Stores> eq2 = new LambdaQueryWrapper<Stores>().eq(Stores::getId, storeItemVo.getStoreId());
            List<Stores> stores = storesMapper.selectList(eq2);
//            System.out.println("stores是"+stores);
            List<StoresVo> convertedStoresVos = StoresConvert.INSTANCE.convertEntityToVo(stores);
            convertedStoresVos.forEach(storesVo -> {
                storesVo.setImages(storeImages.stream().map(StoreImages::getImageUrl).toList());
            });
            storesVos.addAll(convertedStoresVos);

        });
        return storesVos;
    }

    @Override
    public List<CostumesVo> searchByName(String name) {
        // 使用like查询匹配名称
        LambdaQueryWrapper<Costumes> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(Costumes::getName, name);

        List<Costumes> costumes = costumesMapper.selectList(wrapper);

        // 转换为VO对象
        List<CostumesVo> costumesVos = CostumesConvert.INSTANCE.convertEntityToVo(costumes);
        costumesVos.forEach(costumesVo -> {
            LambdaQueryWrapper<CostumeImages> eq1 = new LambdaQueryWrapper<CostumeImages>().eq(CostumeImages::getCostumeId, costumesVo.getId()).eq(CostumeImages::getIsMain, 1);
            costumesVo.setUrl(costumeImagesMapper.selectOne(eq1).getUrl());
        });
        return costumesVos;
    }




    @Override
    public Map<String, Object> getTopCostume() {
        // 查询销量最高的服装
        LambdaQueryWrapper<Costumes> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Costumes::getSalesVolume)
                .last("LIMIT 1");

        Costumes topCostume = costumesMapper.selectOne(wrapper);

        if (topCostume == null) {
            return null;
        }

        // 查询对应的主图
        CostumeImages mainImage = costumeImagesMapper.selectOne(
                new LambdaQueryWrapper<CostumeImages>()
                        .eq(CostumeImages::getCostumeId, topCostume.getId())
                        .eq(CostumeImages::getIsMain, 1)
        );

        // 构建返回数据
        Map<String, Object> result = new HashMap<>();
        result.put("id", topCostume.getId());
        result.put("name", topCostume.getName());
        result.put("sales", topCostume.getSalesVolume());
        result.put("price", topCostume.getPrice());
        result.put("mainImage", mainImage != null ? mainImage.getUrl() : null);

        return result;
    }

    /**
     *
     *上传图片
     * @param id
     * @param files
     * @return
     */
    @Transactional
    @Override
    public Result<Boolean> addImages(Long id, List<MultipartFile> files) {

        if (files == null || files.isEmpty()) {
            return Result.ok(false); // 如果没有文件，直接返回失败
        }

        int insert =0;
        for (MultipartFile file : files) {
            CostumeImages costumeImages = new CostumeImages();
            String imageUrl = FileUtil.uploadFile(file, uploadDir);
            costumeImages.setCostumeId(id);
            costumeImages.setUrl(imageUrl);
            insert = costumeImagesMapper.insert(costumeImages);
        };

        return Result.ok(insert>0);
    }

    @Override
    public List<Map<String, Object>> getHotCostumesWithPage(Integer pageNo, Integer pageSize, Integer imageCount) {
        // 分页查询热门服装
        Page<Costumes> page = new Page<>(pageNo, pageSize);
        LambdaQueryWrapper<Costumes> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Costumes::getSalesVolume);

        Page<Costumes> costumesPage = costumesMapper.selectPage(page, wrapper);

        // 构建返回数据
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (Costumes costume : costumesPage.getRecords()) {
            Map<String, Object> costumeMap = new HashMap<>();
            costumeMap.put("id", costume.getId());
            costumeMap.put("name", costume.getName());
            costumeMap.put("sales", costume.getSalesVolume());
            costumeMap.put("price", costume.getPrice());

            // 处理图片列表
            List<String> imageUrls = new ArrayList<>();
            if (imageCount == null) {
                // 如果未指定图片数量，只返回主图
                CostumeImages mainImage = costumeImagesMapper.selectOne(
                        new LambdaQueryWrapper<CostumeImages>()
                                .eq(CostumeImages::getCostumeId, costume.getId())
                                .eq(CostumeImages::getIsMain, 1)
                );
                if (mainImage != null) {
                    imageUrls.add(mainImage.getUrl());
                }
            } else {
                // 如果指定了图片数量，先查询主图，再补充其他图片
                List<CostumeImages> images = costumeImagesMapper.selectList(
                        new LambdaQueryWrapper<CostumeImages>()
                                .eq(CostumeImages::getCostumeId, costume.getId())
                                .orderByDesc(CostumeImages::getIsMain)  // 主图优先
                                .last("LIMIT " + imageCount)
                );
                for (CostumeImages image : images) {
                    imageUrls.add(image.getUrl());
                }
            }

            costumeMap.put("images", imageUrls);
            resultList.add(costumeMap);
        }
        return resultList;
    }


}